package main

import (
	"fmt"
	"google.golang.org/grpc"
	"grpc_starter/grpc_stream/pb"
	"net"
	"sync"
	"time"
)

type server struct{}

func (s *server) GetStream(reqData *pb.StreamReqData, streamServer pb.Greet_GetStreamServer) error {
	count := 1
	for {
		count++

		err := streamServer.Send(&pb.StreamResData{
			Data: fmt.Sprintf("%s %v %v %v", reqData.Message, time.Now().Unix(), reqData.Gender, reqData.Map),
		})
		if err != nil {
			return err
		}

		if count >= 20 {
			break
		}
		time.Sleep(time.Second)
	}
	return nil
}

func (s *server) PutStream(streamServer pb.Greet_PutStreamServer) error {
	for {
		if data, _ := streamServer.Recv(); data == nil {
			break
		} else {
			fmt.Println("get client data: ", data.Message)
		}
	}

	return nil
}

func (s *server) AllStream(streamServer pb.Greet_AllStreamServer) error {
	var wg sync.WaitGroup

	wg.Add(2)

	go func() {
		defer wg.Done()
		for {
			recData, _ := streamServer.Recv()
			fmt.Println("got client data: ", recData.Message)
		}
	}()

	go func() {
		wg.Done()
		for {
			_ = streamServer.Send(&pb.StreamResData{
				Data: "i'm server send message",
			})
			time.Sleep(time.Second)
		}

	}()
	wg.Wait()

	return nil
}

func main() {
	listen, _ := net.Listen("tcp", "127.0.0.1:5001")

	s := grpc.NewServer()

	pb.RegisterGreetServer(s, new(server))

	_ = s.Serve(listen)
}
